﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TheOutLetLibrary.Infraestrutura;
using TheOutLetLibrary.Dominio;
using Ninject;
using Ninject.Parameters;
using System.Globalization;
using System.Data.OleDb;
using System.IO;

namespace TheOutLetUI {

    public partial class FrmCargaNF : Form {

        private MeuKernel kernel;
        private IFactoryDAO factoryDAO;

        private static FrmCargaNF frmCargaNF = null;

        public static FrmCargaNF Instance() {
            if(frmCargaNF == null) {
                frmCargaNF = new FrmCargaNF();
            }
            return frmCargaNF;
        }

        private FrmCargaNF() {            
            InitializeComponent();
        }

        private void FrmCargaNF_Load(object sender, EventArgs e) {

            kernel = new MeuKernel();
            factoryDAO = kernel.Get<IFactoryDAO>();

            CarregaComboRemessa();
            CarregaComboEmpresa();

            btnCarregarNFs.Enabled = false;
        }

        private void CarregaComboEmpresa() {

            using(OleDbConnection conexao = factoryDAO.GetConexao) {

                try {
                    conexao.Open();
                    OleDbTransaction transacao = conexao.BeginTransaction();
                    IEmpresaDAO empresaDAO = factoryDAO.GetEmpresaDAO(transacao);

                    OleDbDataReader reader = empresaDAO.CarregarEmpresas();
                    DataTable empresas = new DataTable();
                    empresas.Columns.Add("idEmpresa", typeof(int));
                    empresas.Columns.Add("nomeEmpresa", typeof(string));
                    while(reader.Read()) {
                        DataRow dataRow = empresas.NewRow();
                        dataRow["idEmpresa"] = reader.GetValue(reader.GetOrdinal("xID_EMPRESA"));
                        dataRow["nomeEmpresa"] = reader.GetValue(reader.GetOrdinal("NMC_EMPRESA"));
                        empresas.Rows.Add(dataRow);
                    }

                    cmbEmpresa.DataSource = empresas;
                    cmbEmpresa.ValueMember = "idEmpresa";
                    cmbEmpresa.DisplayMember = "nomeEmpresa";
                    cmbEmpresa.SelectedIndex = -1;   
                } catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void CarregaComboRemessa() {

            using(OleDbConnection conexao = factoryDAO.GetConexao) {

                try {
                    conexao.Open();
                    OleDbTransaction transacao = conexao.BeginTransaction();
                    IRemessaDAO remessaDAO = factoryDAO.GetRemessaDAO(transacao);

                    OleDbDataReader reader = remessaDAO.CarregarRemessas();
                    DataTable remessas = new DataTable();
                    remessas.Columns.Add("idRemessa", typeof(int));
                    remessas.Columns.Add("detalhesRemessa", typeof(string));
                    remessas.Columns.Add("idEmpresa", typeof(int));
                    DataRow newRow = remessas.NewRow();
                    newRow["idRemessa"] = 0;
                    newRow["detalhesRemessa"] = "Nova remessa";
                    newRow["idEmpresa"] = 0;
                    remessas.Rows.Add(newRow);
                    while(reader.Read()) {
                        string detalhe = string.Format(
                            "Remessa {0} da {1} em {2}",
                            reader.GetValue(reader.GetOrdinal("xID_REMESSA")),
                            reader.GetValue(reader.GetOrdinal("NMC_EMPRESA")),
                            reader.GetValue(reader.GetOrdinal("DT_RECEBIMENTO_REMESSA")));
                        newRow = remessas.NewRow();
                        newRow["idRemessa"] = reader.GetValue(reader.GetOrdinal("xID_REMESSA"));
                        newRow["detalhesRemessa"] = detalhe;
                        newRow["idEmpresa"] = reader.GetValue(reader.GetOrdinal("xID_EMPRESA"));
                        remessas.Rows.Add(newRow);
                    }
                    cmbRemessa.DataSource = remessas;
                    cmbRemessa.ValueMember = "idRemessa";
                    cmbRemessa.DisplayMember = "detalhesRemessa";
                } catch(Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void btnSelecionarNFs_Click(object sender, EventArgs e) {
            btnCarregarNFs.Enabled = false;
            LimpaGridArquivosXml();
            FolderBrowserDialog folderBrowse = new FolderBrowserDialog();
            if (folderBrowse.ShowDialog() == DialogResult.OK) {
                DirectoryInfo dir = new DirectoryInfo(folderBrowse.SelectedPath);
                FileInfo[] arquivosXml = dir.GetFiles("*.xml");
                if(arquivosXml.Count() > 0) {
                    foreach(FileInfo arquivo in arquivosXml) {
                        DataGridNotasFiscais.Rows.Add(arquivo.FullName);
                    }
                    btnCarregarNFs.Enabled = true;
                } else {
                    MessageBox.Show("Nenhum arquivo xml encontrado", "Carga de Notas Fiscais");
                }
            }
        }

        private void LimpaGridArquivosXml() {
            DataGridNotasFiscais.Rows.Clear();
            btnCarregarNFs.Enabled = false;
        }

        private void btnCarregarNFs_Click(object sender, EventArgs e) {

            CarregadorNF carregadorNF = new CarregadorNF(
                factoryDAO,
                (int)cmbRemessa.SelectedValue,
                (int)cmbEmpresa.SelectedValue,
                DataGridNotasFiscais.Rows.Count);

            for(int r = 0; r < DataGridNotasFiscais.Rows.Count; r++) {
                DataGridNotasFiscais.Rows[r].Cells[1].Value =
                    carregadorNF.ImporteNF(DataGridNotasFiscais.Rows[r].Cells[0].Value.ToString());
            }

            CarregaComboRemessa();

            btnCarregarNFs.Enabled = false;

        }

        private void cmbRemessa_SelectedIndexChanged(object sender, EventArgs e) {
            DataRowView dataRow = (DataRowView)cmbRemessa.SelectedItem;
            cmbEmpresa.SelectedValue = dataRow["idEmpresa"];
            cmbEmpresa.Enabled = cmbRemessa.SelectedIndex == 0;
        }

        private void cmbEmpresa_SelectedIndexChanged(object sender, EventArgs e) {
            btnSelecionarNFs.Enabled = cmbEmpresa.SelectedIndex != -1;
        }

    }
}
